<template>
  <van-popup
    v-model:show="shows"
    teleport="body"
    position="right"
    :z-index="zIndex"
    :style="{
      width: '100%',
      height: '100%',
      overflow: 'auto',
      position: 'absolute',
      top: 0,
      transform: 'none',
      '-webkit-transform': 'none',
      transition: 'none',
      '-webkit-transition': 'none'
    }"
  >
    <div class="contents">
      <van-nav-bar title="选择城市" left-arrow @click-left="onClickLeft" />
      <van-field
        v-model="qstr"
        clearable
        placeholder="输入城市名称搜索"
        @update:model-value="resetData"
        :style="{ margin: '10px 0px' }"
      >
      </van-field>
      <van-index-bar v-if="Object.getOwnPropertyNames(newData).length">
        <template v-for="(item, key) in newData" :key="key">
          <van-index-anchor :index="key" />
          <template v-for="(jtem, j) in item" :key="key + j">
            <van-cell @click="onchange(jtem)" :title="jtem.CityName" />
          </template>
        </template>
      </van-index-bar>
      <div v-else class="no-data">
        <van-empty description="未查询到城市数据" />
      </div>
    </div>
  </van-popup>
</template>

<script>
import cityJson from "./cityJson";
import { getCurrentInstance, onMounted, reactive, toRefs, watch } from "vue";
import storage from "../../assets/util/storage";
export default {
  props: {
    zIndex: {
      type: Number,
      default: () => {
        return 1000;
      }
    },
    show: Boolean // 是否显示
  },
  emits: ["update:show", "change"],
  name: "CheckCity",
  setup(props) {
    const { proxy } = getCurrentInstance();
    const pageData = reactive({
      newData: {},
      shows: props.show,
      qstr: ""
    });
    // 打开补录弹窗
    watch(
      () => props.show,
      item => {
        pageData.shows = item;
      },
      { immediate: true }
    );
    const pageMethods = {
      resetData(qstr) {
        const data = JSON.parse(JSON.stringify(cityJson));
        let obj = {};
        data.forEach(item => {
          let addObj = obj[item.CityGroupName];
          if (
            (qstr &&
              (item.CityName === qstr || item.CityName.indexOf(qstr) > -1)) ||
            !qstr
          ) {
            if (addObj) {
              addObj.push(item);
            } else {
              obj[item.CityGroupName] = [item];
            }
          }
        });
        pageData.newData = obj;
      },
      onClickLeft() {
        proxy.$emit("update:show", false);
      },
      onchange(data) {
        pageMethods.onClickLeft();
        proxy.$emit("change", data);
      }
    };
    onMounted(() => {
      pageMethods.resetData();
    });
    return {
      ...toRefs(pageData),
      ...pageMethods
    };
  }
};
</script>

<style scoped lang="less"></style>
